import axios from 'axios'
import {Message} from 'element-ui'
import router from '../router'
// 创建一个axios实例
const service = axios.create({
  baseURL: window.config.BASE_API, // api的base_url，在config下的dev.evn.js和prod.env.js中配置
  timeout: 60000
});

service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 请求拦截器
service.interceptors.request.use(function (config) {
  config.headers["token"] = localStorage.getItem("token");
  return config;
}, function (error) {
  return Promise.reject(error);
});

// 响应拦截器
service.interceptors.response.use((res) => {
  if (res.status === 200 && res?.data?.data === '401' && router.history.current.path !== '/Login') {
    /*Message({
      message: "登录信息失效，请重新登录",
      type: 'warning',
      duration: 5 * 1000
    });*/
    router.push({path: '/Login'});
  }
  if (res.status === 200 && router.history.current.path !== '/Login') {
    let token_iax_time = localStorage.getItem('token_iax_time');
    if (new Date().getTime() - Number(token_iax_time) > window.config.TOKEN_EXPIRES * 60 * 1000) {
      axios.get(window.config.BASE_API + '/auth/refreshToken', {
        headers: {
          token: localStorage.getItem('token'),
          'Content-Type': 'application/json'
        }
      }).then(({data})=>{
        if (data.success) {
          const token = data.data === '401' ? '' : data.data;
          localStorage.setItem('token', token);
          localStorage.setItem("token_iax_time", new Date().getTime().toString());
        }
      }).catch(err => {
        Message({
          message: "刷新token失败",
          type: 'error',
          duration: 5 * 1000
        });
      })
    }
  }
  if (res.status === 654) {
    Message({
      message: "请求超时",
      type: 'error',
      duration: 5 * 1000
    });
  }
  if (res.status !== 200) {
    Message({
      message: "数据返回有误",
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(res);
  }
  return res;
}, (error) => {
  console.log('promise error:' + error);
  return Promise.reject(error);
});

export default service
